#include <jni.h>
#include <string>

extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/imgutils.h"
#include "libswscale/swscale.h"
#include <libavutil/time.h>
#include "libswresample/swresample.h"
}
#include <android/log.h>
#include <android/native_window_jni.h>
#include "LYFFmpeg.h"

#define LOGD(...) __android_log_print(ANDROID_LOG_INFO,"liuyi",__VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, "liuyi", __VA_ARGS__)

_JavaVM *javaVM = NULL;
LYCallJava *callJava = NULL;
LYFFmpeg *ffmpeg = NULL;
LYPlaystatus *playstatus = NULL;
extern "C"
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    jint result = -1;
    javaVM = vm;
    JNIEnv *env;
    if(vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
        return result;
    }
    return JNI_VERSION_1_4;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1parpared(JNIEnv *env, jobject instance,
                                                           jstring source_) {
    const char *source = env->GetStringUTFChars(source_, 0);
    if(ffmpeg == NULL) {
        if(callJava == NULL) {
            callJava = new LYCallJava(javaVM, env, &instance);
        }
        playstatus = new LYPlaystatus();
        ffmpeg = new LYFFmpeg(playstatus, callJava, source);
        ffmpeg->parpared();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1start(JNIEnv *env, jobject thiz) {
    if(ffmpeg != NULL) {
        ffmpeg->start();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1resume(JNIEnv *env, jobject thiz) {
    if(ffmpeg != NULL) {
        ffmpeg->resume();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1pause(JNIEnv *env, jobject thiz) {
    if(ffmpeg != NULL) {
        ffmpeg->pause();
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1mute(JNIEnv *env, jobject thiz, jint mute) {
    if(ffmpeg != NULL) {
        ffmpeg->setMute(mute);
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1volume(JNIEnv *env, jobject thiz, jint percent) {
    if(ffmpeg != NULL) {
        ffmpeg->setVolume(percent);
    }
}

extern "C"
JNIEXPORT void JNICALL
Java_com_luisliuyi_demo_ffmpeg_player_LYPlayer_n_1seek(JNIEnv *env, jobject thiz, jint secds) {
    if(ffmpeg != NULL)  {
        ffmpeg->seek(secds);
    }
}